package com.bitin.module.user.service;

import com.bitin.common.constant.Gender;
import com.bitin.module.user.domain.entity.Employee;
import com.bitin.module.user.domain.repository.EmployeeRepository;
import jakarta.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.Query;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Mr.Lu
 * @Datetime 2024/8/13 23:04
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeRepository employeeRepository;

    public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    @Override
    public BigDecimal total() {
        Specification<Employee> specification = (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(builder.equal(root.get("sex"), Gender.MALE));

            return query.distinct(true)
                    .multiselect(builder.sum(root.get("salary")))
                    .where(predicates.toArray(new Predicate[predicates.size()])).getGroupRestriction();
        };

//        List<Employee> all = this.employeeRepository.findAll(specification);
//        System.err.println(all);

        Query salary = employeeRepository.salary(specification);
        System.err.println(salary);

        return BigDecimal.ZERO;
    }

    @Override
    @Transactional
    public Employee save(Employee employee) {
        return employeeRepository.save(employee);
    }

    @Override
    public List<Employee> employees() {
        return employeeRepository.findAll();
    }
}
